package com.example.lenovo.asia5b.commodity.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.lenovo.asia5b.commodity.adapter.AllEvaluateDetAdapter;
import com.example.lenovo.asia5b.commodity.bean.AllEvaluateBean;
import com.example.lenovo.asia5b.commodity.bean.AllEvaluateDetBean;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.BaseActivity;
import fay.frame.ui.U;
import com.example.lenovo.asia5b.ui.CircleImageView;
import com.example.lenovo.asia5b.ui.DownloadPicture;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.ui.PullToRefreshLayout;
import com.example.lenovo.asia5b.ui.photoview.ImagePagerActivity;
import com.example.lenovo.asia5b.util.DensityUtil;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.Setting;
import com.example.lenovo.asia5b.util.keyboardUtil;

import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;

/**
 * Created by lenovo on 2017/7/1.
 */

public class EvaluateDetActivity extends BaseActivity implements ICallBack, PullToRefreshLayout.OnRefreshListener{
    private AllEvaluateDetAdapter adapter;
    private ListView lv_evaluate_det;
    private View titView;
    private EditText edit_send;
    private LinearLayout ll_imag ;
    private  ArrayList<String> urls_3 ;
    private String comment_id;
    private int page  = 1;
    private int countPage = 0;
    private PullToRefreshLayout pullToRefreshLayout;
    private LoadingDalog loadingDalog;
    private List<AllEvaluateDetBean> lists = null;

    private  ImageView image_head,image_thumb;
    private TextView txt_name,txt_goods_attr,txt_content;
    private  TextView txt_goods_name,txt_market_price_rm,txt_shop_price_rm,txt_size;
    private String goods_id;
    private boolean isSelect = false;
    private  String type = "2";
    private  boolean islike = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_evaluate_det);
        initView();

        urls_3 = new ArrayList<String>();
//        urls_3.add("http://img.my.csdn.net/uploads/201410/19/1413698837_7507.jpg");
        AllEvaluateDetData();

    }

    public void initView() {
        AllEvaluateBean bean = null;
        if (getIntent().hasExtra("comment_id")) {
            bean = (AllEvaluateBean)getIntent().getSerializableExtra("comment_id");
            comment_id = bean.comment_id;
            if (bean.ishave.equals("1")) {
                type = "1";
                F.id(R.id.image_like).image(R.drawable.rate_like_sel_button);
                islike = true;
            }
        }
        loadingDalog = new LoadingDalog(EvaluateDetActivity.this);
        loadingDalog.show();
        pullToRefreshLayout = ((PullToRefreshLayout)findViewById(R.id.refresh_view));
        pullToRefreshLayout.setOnRefreshListener(this);
        F.id(R.id.btn_change_information).clicked(this);

        F.id(R.id.public_title_name).text(getResources().getString(R.string.pjxq));
        F.id(R.id.public_btn_left).clicked(this);
        F.id(R.id.ll_comment).clicked(this);
        F.id(R.id.ll_like).clicked(this);
        F.id(R.id.txt_send).clicked(this);
        lv_evaluate_det = (ListView)findViewById(R.id.lv_evaluate_det);
        edit_send = (EditText)findViewById(R.id.edit_send);
        adapter = new AllEvaluateDetAdapter(this);
        titView = LayoutInflater.from(this).inflate(R.layout.tit_evaluate_det,null);

        lv_evaluate_det.addHeaderView(titView);
//        lv_evaluate_det.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                F.id(R.id.ll_comment_a).visibility(View.GONE);
//                F.id(R.id.ll_send).visibility(View.VISIBLE);
//                edit_send.requestFocus();
//                keyboardUtil.showInputMethod(EvaluateDetActivity.this,edit_send);
//            }
//        });
        lv_evaluate_det.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        // 触摸按下时的操作
                        break;
                    case MotionEvent.ACTION_MOVE:
                        // 触摸移动时的操作
                        keyboardUtil.HideKeyboard(titView);
                        F.id(R.id.ll_comment_a).visibility(View.VISIBLE);
                        F.id(R.id.ll_send).visibility(View.GONE);
                        break;
                    case MotionEvent.ACTION_UP:
                        // 触摸抬起时的操作
                        break;
                }

                return false;
            }
        });
        lv_evaluate_det.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
            }
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // 当不滚动时
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (view.getLastVisiblePosition() == view.getCount() - 1) {
                        if (page < countPage) {
                            page += 1;
                            AllEvaluateDetData();
                        } else {
                            TextView load_tv = (TextView)findViewById(R.id.load_tv);
                            load_tv.setText(getResources().getString(R.string.no_more_data));
                            load_tv.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        });

        //评论
        if(null != bean) {
            ll_imag = (LinearLayout) titView.findViewById(R.id.ll_imag);
            initTitView(bean);
            image_head = (CircleImageView) titView.findViewById(R.id.image_head);
            txt_name = (TextView) titView.findViewById(R.id.txt_name);
            txt_goods_attr = (TextView) titView.findViewById(R.id.txt_goods_attr);
            txt_content = (TextView) titView.findViewById(R.id.txt_content);
            DownloadPicture.loadNetwork(bean.avatar,image_head);
            txt_name.setText(bean.user_name);
            txt_content.setText(bean.content);
            txt_goods_attr.setText(bean.add_time+"\t"+bean.goods_attr);
        }
        //商品
        image_thumb = (ImageView)titView.findViewById(R.id.image_thumb);
        txt_goods_name = (TextView)titView.findViewById(R.id.txt_goods_name);
        txt_market_price_rm = (TextView)titView.findViewById(R.id.txt_market_price_rm);
        txt_shop_price_rm = (TextView)titView. findViewById(R.id.txt_shop_price_rm);
        txt_size = (TextView)titView.findViewById(R.id.txt_size);

        lv_evaluate_det.setAdapter(adapter);
    }

    /**
     * 回复评论列表
     */
    public void  AllEvaluateDetData() {
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.GOODS_RECOMMLIST;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"comment_id"+comment_id,"page"+page,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("comment_id", comment_id);
            parmaMap.put("page",""+page);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 0);
        }catch (Exception e) {

        }
    }

    /**
     *发送评论
     */
    public void sendData() {
        try {
            if (null ==  getUserBean()) {
                U.Toast(EvaluateDetActivity.this,getResources().getString(R.string.qdlzh));
                return;
            }
            if (TextUtils.isEmpty(edit_send.getText().toString())) {
                return;
            }
            loadingDalog.show();

            String content = edit_send.getText().toString();
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.GOODS_COMMENT;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"comment_id"+comment_id,"user_id"+user_id,"goods_id"+goods_id,"content"+content,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("comment_id", comment_id);
            parmaMap.put("user_id",""+user_id);
            parmaMap.put("goods_id",""+goods_id);
            parmaMap.put("content",""+content);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 1);
        }catch (Exception e) {

        }
    }

    public void likeData() {
        try {
            if (null ==  getUserBean()) {
                U.Toast(EvaluateDetActivity.this,getResources().getString(R.string.qdlzh));
                return;
            }
            loadingDalog.show();
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.COMMENT_LIKE;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String user_id = getUserBean().user_id;
            String[] sort = {"comment_id"+comment_id,"type"+type,"user_id"+user_id,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("comment_id", comment_id);
            parmaMap.put("type", type);
            parmaMap.put("user_id",user_id);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 2);
        }catch (Exception e) {

        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.public_btn_left:
                if (isSelect) {
                    intent = new Intent();
                    intent.putExtra("222",2222);
                    this.setResult(0, intent);
                }
                finish();
                break;
            case R.id.btn_immediately_on:
                U.Toast(this,getResources().getString(R.string.cg));
                finish();
                break;
            case  R.id.ll_comment:
                F.id(R.id.ll_comment_a).visibility(View.GONE);
                F.id(R.id.ll_send).visibility(View.VISIBLE);
                edit_send.requestFocus();
               keyboardUtil.showInputMethod(EvaluateDetActivity.this,edit_send);
                break;
            case R.id.txt_send:
                sendData();
                break;
            case R.id.ll_like:
                likeData();
                break;
            default:
                break;
        }
    }


    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json =  (JSONObject)result;
                        int state = (int)json.getInt("State");
                        if (state == 0) {
                            JSONObject paging = json.getJSONObject("paging");
                            if (null!=paging.getString("page") && "1".equals(paging.getString("page"))) {
                                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                                initPaging(paging);
                                JSONArray account = json.getJSONArray("recomments");
                                lists = Logic.getListToBean(account,new AllEvaluateDetBean());
                                adapter.setLists(lists);
                                adapter.notifyDataSetChanged();

                                //商品
                                JSONArray jsonArray = json.getJSONArray("recomm_goods");
                                JSONObject recomm_goods = jsonArray.getJSONObject(0);

                                goods_id = recomm_goods.getString("goods_id");
                                DownloadPicture.loadHearNetwork(recomm_goods.getString("goods_thumb"),image_thumb);
                                txt_goods_name.setText(recomm_goods.getString("goods_name"));
                                txt_market_price_rm.setText("RM"+recomm_goods.getString("market_price_rm"));
                                txt_market_price_rm.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG );
                                txt_shop_price_rm.setText("RM"+recomm_goods.getString("shop_price_rm"));
                                txt_size.setText("("+lists.size()+")");
                            } else if(null!=paging.getString("page") && !"1".equals(paging.getString("page"))){
                                pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                                JSONArray account = (JSONArray) json.get("comments");
                                if (null != account && account.length() > 0) {
                                    List<AllEvaluateDetBean> listBean  =  Logic.getListToBean(account,new AllEvaluateDetBean());
                                    for (int i = 0; i < listBean.size(); i++) {
                                        lists .add(listBean.get(i));
                                    }
                                    adapter .setLists(lists);
                                    adapter .notifyDataSetChanged();
                                } else {
                                    page = page - 1;
                                }

                            }
                        }  else if(state == 1){
                            U.Toast(EvaluateDetActivity.this,getResources().getString(R.string.qmsb));
                        }else if(state == 2){
                            U.Toast(EvaluateDetActivity.this,getResources().getString(R.string.cscw));
                        }else if(state == 3){
                            U.Toast(EvaluateDetActivity.this,getResources().getString(R.string.wdl));
                        }else if(state == 4){
                            U.Toast(EvaluateDetActivity.this,getResources().getString(R.string.mysj));
                        }
                    } catch (Exception e) {
                    }
                }
                loadingDalog.dismiss();
            }
            if (action == 1) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0 ) {
                            loadingDalog.show();
                            AllEvaluateDetData();
                            edit_send.setText("");
                            isSelect = true;
                        } else if(state == 1){
                            U.Toast(EvaluateDetActivity.this,getResources().getString(R.string.qmsb));
                        }else if(state == 2){
                            U.Toast(EvaluateDetActivity.this,getResources().getString(R.string.cscw));
                        }else if(state == 3){
                            U.Toast(EvaluateDetActivity.this,getResources().getString(R.string.wdl));
                        }else if(state == 4){
                            U.Toast(EvaluateDetActivity.this,getResources().getString(R.string.mysj));
                        }
                    }catch (Exception e) {

                    }
                }
                loadingDalog.dismiss();
            }
            if (action == 2) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0 ) {
                            U.Toast(EvaluateDetActivity.this,getResources().getString(R.string.cg));
                            isSelect = true;
                            if (islike) {
                                islike = false;
                                type = "2";
                                F.id(R.id.image_like).image(R.drawable.rate_like_button);
                            } else {
                                islike = true;
                                type = "1";
                                F.id(R.id.image_like).image(R.drawable.rate_like_sel_button);
                            }
                        } else if(state == 1){
                            U.Toast(EvaluateDetActivity.this,getResources().getString(R.string.qmsb));
                        }else if(state == 2){
                            U.Toast(EvaluateDetActivity.this,getResources().getString(R.string.cscw));
                        }else if(state == 3){
                            U.Toast(EvaluateDetActivity.this,getResources().getString(R.string.wdl));
                        }else if(state == 4){
                            U.Toast(EvaluateDetActivity.this,getResources().getString(R.string.mysj));
                        }
                    }catch (Exception e) {

                    }
                }
                loadingDalog.dismiss();
            }
        }
    };

    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }


    public void initTitView(AllEvaluateBean bean ) {
        try {
            JSONArray jsonArray = new JSONArray(bean.cmmt_img);
            final  ArrayList<String> urls2 = new ArrayList<String>();
            int width = DensityUtil.getScreenWidth(EvaluateDetActivity.this) - 90;
            LinearLayout mLayout = null;
            for (int i = 0; i < jsonArray.length(); i++) {
                if (i % 3 == 0) {
                    mLayout = new LinearLayout(EvaluateDetActivity.this);
                    mLayout.setLayoutParams(new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT));
                    mLayout.setOrientation(LinearLayout.HORIZONTAL);
                    mLayout.setWeightSum(3);
                    ll_imag.addView(mLayout);
                }
                View hotSaleView = LayoutInflater.from(EvaluateDetActivity.this).inflate(R.layout.item_hot_sale, null);
                hotSaleView.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
                ImageView image_commodity = (ImageView) hotSaleView.findViewById(R.id.image_commodity);
                TextView txt_name = (TextView) hotSaleView.findViewById(R.id.txt_name);

                image_commodity.setLayoutParams(new LinearLayout.LayoutParams(
                        width / 3,
                        width / 3));
                image_commodity.setTag(i);
                String cmmt_img = jsonArray.getString(i);
                urls2.add(cmmt_img);
                DownloadPicture.loadNetwork(cmmt_img, image_commodity);
                image_commodity.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        imageBrower((int) view.getTag(), urls2);
                    }
                });
                txt_name.setVisibility(View.GONE);
                mLayout.addView(hotSaleView);
            }
        } catch (Exception e) {

        }
    }

    /**
     * 打开图片查看器
     *
     * @param position
     * @param urls2
     */
    protected void imageBrower(int position, ArrayList<String> urls2) {
        Intent intent = new Intent(EvaluateDetActivity.this, ImagePagerActivity.class);
        // 图片url,为了演示这里使用常量，一般从数据库中或网络中获取
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, urls2);
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
        startActivity(intent);
    }

    public void initPaging(JSONObject json) throws JSONException {
        String pageSizeString = json.getString("count");
        String countPageString = json.getString("countpage");
        String pageString = json.getString("page");
        if (pageSizeString != null && countPageString != null && pageString != null) {
            countPage = Integer.parseInt(countPageString);
            if (countPage <=1) {
                pullToRefreshLayout.stopLoadMore();
            }
        }
    }

    /**
     * 向下刷新
     */
    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        loadingDalog.show();
        page = 1;
        AllEvaluateDetData();
    }

    /**
     * 向上加载
     */
    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //判断用户是否点击的是返回键
        if(keyCode == KeyEvent.KEYCODE_BACK){
            if (isSelect) {
                Intent intent = new Intent();
                intent.putExtra("222",2222);
                this.setResult(0, intent);
            }
            finish();

        }
        return false;
    }
}
